"""
    @File: read_ini.py
    @Auth: lanhui 
    @Date: 2022/7/21-15:36
    @Desc: 
    @Ver : 0.0.0
"""

import configparser
import re

class ParseConFile(object):

    def __init__(self, ini_file_path: str):
        self.file = ini_file_path
        with open(self.file, encoding="utf8") as f:
            content = f.read()
            content = re.sub(r"\xfe\xff", "", content)
            content = re.sub(r"\xff\xfe", "", content)
            content = re.sub(r"\xef\xbb\xbf", "", content)
            content = re.sub(r"\ufeff", "", content)
        with open(self.file, 'w', encoding="utf8") as f:
            f.write(content)
        self.config = configparser.ConfigParser()
        self.config.read(self.file, encoding='utf-8')

    def get_all_sections(self):
        """获取所有的section，返回一个列表"""
        return self.config.sections()

    def get_all_options(self, section):
        """获取指定section下所有的option, 返回列表"""
        return self.config.options(section)

    def get_all_value_dict(self, section):
        """获取指定section下所有的option和对应的数据，返回字典"""
        value = dict(self.config.items(section))
        return value
    def get_option_value(self, section, option):
        """获取指定section下所有的option和对应的数据，返回字典"""
        try:
            value = self.config.get(section, option)
            return value
        except configparser.NoOptionError as e:
            print('error:', e)
            return "error"
    def get_zentao_user(self):
        """获取指定section, 指定option对应的数据, 返回元祖和字符串"""
        try:
            section = "zentao"
            option = "user"
            locator_user = self.config.get(section, option)

            section = "zentao"
            option = "passwd"
            locator_passwd = self.config.get(section, option)
            return locator_user, locator_passwd
        except configparser.NoOptionError as e:
            print('error:', e)
        return 'error: No option "{}" in section: "{}"'.format(option, section)

    def set_zentao_user(self, user, passwd):
        """获取指定section, 指定option对应的数据, 返回元祖和字符串"""
        try:
            section = "zentao"
            option = "user"
            self.config.set(section, option, user)

            section = "zentao"
            option = "passwd"
            self.config.set(section, option, passwd)
        except configparser.NoOptionError as e:
            print('error:', e)
